<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <%@page import="java.util.Calendar"%>
    <%@page import="managers.MngRates"%>
    <%@page import="business.Current"%>
    <%
        String user = "", msg = "";
        int userID = 0;
        
        HttpSession sess = request.getSession();
        Calendar cal = Calendar.getInstance();
        MngRates mngRat = new MngRates();

        if (sess.getAttribute("userID") != null) {
            userID = Integer.parseInt(sess.getAttribute("userID").toString());
            System.out.println("userID: " + userID);
        }

        if (request.getParameter("txtUser") != null && request.getMethod() == "POST") {
    %>
            <%@page import="managers.MngUsers"%>
    <%
            user = request.getParameter("txtUser");
            String pass = request.getParameter("txtPass");
            //int company = Integer.parseInt(request.getParameter("selCompany"));
            int company = 1;
            float rate = Float.parseFloat(request.getParameter("txtRate"));

            MngUsers mUsers = new MngUsers();

            userID = mUsers.login(user, pass);

            if (userID > 0) {
                sess.setAttribute("userID", userID);
                sess.setAttribute("company", company);
                mngRat.verifyRate(cal, 2, rate);
                response.sendRedirect("./");
            }	else msg = "Usuario o Contraseña incorrecta.";
        }

        if (request.getParameter("logout") != null && request.getMethod() == "POST") {
            sess.invalidate();
            userID = 0;
            response.sendRedirect("./");
        }
    %>
	<meta charset="utf-8">
	<title>Sistema de Gestión Textil</title>
    <link type="image/x-icon" href="favicon.png" rel="shortcut icon" />
	<link href="css/default.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/basics.js"></script>

    <% if (userID > 0) { %>
        <script type="text/javascript" src="js/ajax.js"></script>
        <!--<script type="text/javascript" src="js/calendar.js"></script>-->
        <script type="text/javascript" src="js/default.js"></script>
        <script type="text/javascript" src="rpc/rpc.jsp"></script>

        <!--
        <link rel="stylesheet" type="text/css" href="forms/css/2.css" />
        <script type="text/javascript" src="forms/js/2.js"></script>
        -->
    <% } else { %>
        <script type="text/javascript">
            function valLogin() {
                var objUser = get('txtUser');
                var objPass = get('txtPass');
                var objRate = get('txtRate');
                //var objCmpy = get('selCompany');

                var user = objUser.value;
                var pass = objPass.value;
                var rate = objRate.value;
                //var cmpy = objCmpy.value;

                var ret = false;

                if (user && pass && rate) ret = true;

                return ret;
            }

            function login() {
                if (get('txtUser').value && get('txtPass').value && get('txtRate').value) {
                    //var win = window.open('','myWin','toolbars=0');
                    //document.frmLogin.target = 'myWin';
                    document.frmLogin.submit();
                    //window.close();
                }
            }

            function setInpFocus() {
                var objUser = get('txtUser');
                if (objUser.value == '') firstControl = 'txtUser';
                else firstControl = 'txtPass';

                get(firstControl).focus();
            }

            var cAlert;

            window.onload = function() {
                setInpFocus();

                cAlert = get('alertCap');
                if (cAlert) {
                    cAlert.show = function(say) {
                        var aSay = get('aSay');
                        clearNode(aSay);
                        var txt = document.createTextNode(say);
                        aSay.appendChild(txt);

                        var sw = document.documentElement.clientWidth;
                        var sh = document.documentElement.clientHeight;

                        var w = this.offsetWidth;
                        var h = this.offsetHeight;

                        var lf = Math.round((sw - w) / 2);
                        var tp = Math.round((sh - h) / 2);

                        this.style.left = lf + 'px';
                        this.style.top = tp + 'px';
                        this.style.visibility = 'visible';
                        gtn(this, 'div')[1].style.width = (w - 14) + 'px';

                        this.capTop = document.createElement('div');
                        this.capTop.id = 'capATop';
                        this.capTop.className = 'floating';
                        getBody().appendChild(this.capTop);

                        this.style.zIndex = this.capTop.style.zIndex + 1;
                    };
                    cAlert.close = function() {
                        getBody().removeChild(this.capTop);
                        cAlert.style.visibility = 'hidden';
                        setInpFocus();
                    };
                }

                var msg = '<%= msg %>';
                if (msg) {
                    cAlert.show('<%= msg %>');
                }
            };

        </script>
    <% } %>
</head>
<body>
    <!-- Confirm Cap -->
    <section id="confirmCap">
        <h2>
            <span>
                Cuadro de Confirmación
            </span>
        </h2>
        <dialog>
            <div>
                <img src="imgs/question.png" alt="Confirmación" />
                <div id="cSay"></div>
                <p>
                    <button onclick="">Si</button>
                    <button onclick="closeCap('confirmCap')">No</button>
                </p>
            </div>
        </dialog>
    </section>
    <!-- Fin de Confirm Cap -->

    <!-- Confirm Cap -->
    <section id="alertCap">
        <h2>
            <span>
                Advertencia
            </span>
        </h2>
        <dialog>
            <div>
                <img src="imgs/notification.png" alt="Confirmación" />
                <div id="aSay"></div>
                <p>
                    <button onclick="cAlert.close();">Aceptar</button>
                </p>
            </div>
        </dialog>
    </section>
    <!-- Fin de Confirm Cap -->

    <%
        if (userID == 0) {
    %>
            <div id="divLogin">
                <div class="title">INICIO DE SESIÓN</div>
                <form name="frmLogin" method="post" action="./" onsubmit="return valLogin();">
                <div class="cntForm">
                    <label>
                        <span>Usuario:</span>
                        <input id="txtUser" name="txtUser" class="minisculas" value="<%= user %>" autofocus />
                    </label>
                    <label>
                        <span>Contraseña:</span>
                        <input id="txtPass" name="txtPass" type="password" onkeyup="if (event.keyCode == 13) login();" />
                    </label>

                    <label>
                        <span>T. Cambio:</span>
                        <%

                            float rat = mngRat.getRate(cal, 2);
                            String rate = "";
                            if (rat > 0) {
                        %>
                                <%@page import="util.DFormat" %>
                        <%		

                                rate = DFormat.format(rat, 3);
                            }
                        %>
                        <input id="txtRate" name="txtRate" class="small decimal3" value="<%= rate %>" <% if (rate != "") out.print("readonly=\"readonly\""); %> onkeyup="if (event.keyCode == 13) login();" />
                    </label>
                    <p>
                        <button type="button" onclick="login();">Enviar</button>
                    </p>
                </div>
                </form>
            </div>
    <% 		
        }   else {
            Current.company = Integer.parseInt(sess.getAttribute("company").toString());
            Current.user = userID;

    %>
            <%@page import="com.google.gson.Gson" %>
            <%@page import="managers.MngPrograms" %>
            <%@page import="java.util.ArrayList" %>
            <%@page import="java.util.Iterator" %>
            <%@page import="business.Module" %>
            <%@page import="business.Program" %>
            <%@page import="business.Current" %>
            <%
                Current.user = 1;
                //Gson gson = new Gson();
                ArrayList<Module> modules = new MngPrograms().getAllPrograms();
                //out.print(gson.toJson(programs));
                Module module;
            %>
            <nav id="navMenu">
                <% 
                    Iterator<Module> iteMod = modules.iterator();
                    while (iteMod.hasNext()) {
                        module = iteMod.next();
                %>
                    <span id="menu<%= module.getId() %>"><%= module.getModule() %></span>
                <% } %>
                <form name="frmLogout" method="post" action="./">
                    <input type="hidden" name="logout" />
                    <span id="menucs" onclick="document.frmLogout.submit();">Cerrar sesión</span>
                </form>
            </nav>

            <blockquote>
                <%
                    ArrayList<Program> programs;
                    Program program;
                    iteMod = modules.iterator();

                    while (iteMod.hasNext()) {
                        module = iteMod.next();
                %>
                <ul id="module<%= module.getId() %>">
                    <%
                        programs = module.getPrograms();
                        Iterator<Program> itePrgs = programs.iterator();

                        while (itePrgs.hasNext()) {
                            program = itePrgs.next();
                    %>
                    <li>
                        <% if (!program.getProgram().equals("-")) { %>
                            <a href="JavaScript:;" onclick="showProgram(<%= program.getId() %>, '<%= program.getProgram() %>', '<%= program.getIcon() %>');">
                                <img alt="<%= program.getProgram() %>" src="imgs/icons/<%= program.getIcon() %>" />
                                <%= program.getProgram() %>
                            </a>
                        <% } else { %>
                            <span></span>
                        <% } %>
                    </li>
                    <%
                        }
                   %>
                </ul>
                <% } %>
            </blockquote>
            <div id="barTop"></div>
            <div id="lineTop"></div>
            
            <section id="win" style="top: 100px; left: 50px; visibility: hidden;">
                <h2>
                    <span>
                        <img src="imgs/icons/users.png" />
                        Tallas
                    </span>

                    <a onclick="removeElement(this.parentNode.parentNode);" title="Cerrar" class="butt-close" href="JavaScript:;"></a>
                    <a onclick="minRestCap(this.parentNode.parentNode, this);" title="Minimizar" class="butt-mm" href="JavaScript:;"></a>
                </h2>
                <article>
                    <div>
                        <img alt="Información" src="imgs/information.png" />
                        <span>Nuevo</span>
                    </div>
                    <dialog>
                        <form onsubmit="return false">
                            <%@ include file="forms/includes.jsp" %>
                            
                        </form>
                    </dialog>
                </article>
            </section>
            <div id="loa" class="none"></div>
    <%  } %>

    <!--<button onclick="test();">Test</button>-->
</body>
</html>